package com.zhaotianhao.check.groupserver.controller;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.zhaotianhao.check.groupserver.common.JsonResult;
import com.zhaotianhao.check.groupserver.common.WebUtils;
import com.zhaotianhao.check.groupserver.entity.Group;
import com.zhaotianhao.check.groupserver.entity.GroupVO;
import com.zhaotianhao.check.groupserver.entity.ItemGroup;
import com.zhaotianhao.check.groupserver.service.IGroupService;
import com.zhaotianhao.check.groupserver.service.IItemGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 检查组 前端控制器
 * </p>
 *
 * @author Z-7
 * @since 2022-03-29
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/group")
public class GroupController {
    @Autowired
    private IGroupService iGroupService;
    @Autowired
    private IItemGroupService iItemGroupService;
    @Resource
    private RedisTemplate redisTemplate;


    @GetMapping ("getGroups")
    public List<Group> getGroups( GroupVO groupVO) {
        String key = "groups";
        String uuid = WebUtils.getRequest().getHeader("uuid");
        if(!redisTemplate.opsForValue().setIfAbsent(uuid,"",20, TimeUnit.MINUTES)){
            log.info("接口重复调用");
            return null;
        }
        // 如果没有缓存 就存一下
        if(!redisTemplate.hasKey(key)){
            redisTemplate.opsForValue().set(key,iGroupService.list());
        }
        return (List<Group>) redisTemplate.opsForValue().get(key);
    }

    @GetMapping("list")
    public JsonResult groupList(GroupVO groupVO, @RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize", defaultValue = "3") int pageSize) {
        PageInfo<Group> page = iGroupService.getPageInfo(groupVO, pageNum, pageSize);
        return JsonResult.successd(page);
    }

    @PostMapping("edit")
    @Transactional(rollbackFor = RuntimeException.class)
    public JsonResult groupAdd(@RequestBody GroupVO groupVO) throws InterruptedException {
        // 防止表单重复提交
        if (!redisTemplate.opsForValue().setIfAbsent(groupVO.getToken(),"",5,TimeUnit.HOURS)) {
            return JsonResult.faild("请稍等");
        }
        Thread.sleep(1000);
        // 修改 删除中建表
        if (groupVO.getId() != null) {
            QueryWrapper<ItemGroup> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("group_id", groupVO.getId());
            List<ItemGroup> middleList = iItemGroupService.list(queryWrapper);
            List<Integer> middleIds = middleList.stream().map(a -> a.getId()).collect(Collectors.toList());
            iItemGroupService.removeByIds(middleIds);
        }
        // 主表的添加
        boolean result = iGroupService.saveOrUpdate(groupVO);

        // 查询中间表
        List<ItemGroup> itemGroups = new ArrayList<>();
        groupVO.getIds().forEach(item -> {
            itemGroups.add(new ItemGroup().setItemId(item).setGroupId(groupVO.getId()));
        });
        // 添加中间表
        boolean flag = iItemGroupService.saveBatch(itemGroups);
        if (result && flag) {
            // 添加reids缓存
            redisTemplate.opsForList().rightPush("redisGroups",groupVO);
            return JsonResult.successd();
        }
        return JsonResult.faild("编辑失败");
    }

    @PostMapping("deleteById")
    @Transactional(rollbackFor = RuntimeException.class)
    public JsonResult deleteById(@RequestBody GroupVO groupVO) {
        // 删除中间表
        groupVO.getIds().forEach(id -> {
            QueryWrapper<ItemGroup> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("group_id", id);
            // 删除中间表
            iItemGroupService.remove(queryWrapper);
            // 删除主表
            iGroupService.removeById(id);
        });

        return JsonResult.successd();
    }

    @GetMapping("getGroupById")
    public Group getGroupById(Integer id) {
        // 主表的查询
        Group group = iGroupService.getById(id);
        GroupVO groupVO = new GroupVO();
        BeanUtils.copyProperties(group, groupVO);
        // 查询中间表
        QueryWrapper<ItemGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id", id);
        List<ItemGroup> list = iItemGroupService.list(queryWrapper);
        List<Integer> middleIds = list.stream().map(item -> item.getId()).collect(Collectors.toList());
        groupVO.setIds(middleIds);
        return groupVO;
    }

    @GetMapping("getToken")
    public JsonResult getToken() {
        return JsonResult.successd(UUID.randomUUID().toString());
    }

    @PostMapping("comboGroups")
    public String comboGroups(@RequestBody GroupVO groupVO) {
        // 查询对应的组
        List<Group> groups = iGroupService.listByIds(groupVO.getIds());
        String groupNames = groups.stream().map(group -> group.getGroupName()).collect(Collectors.joining(","));
        String itemNames = "";
        for (Group group : groups) {
            QueryWrapper<ItemGroup> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("group_id",group.getId());
            List<ItemGroup> itemGroups = iItemGroupService.list(queryWrapper);
            List<Integer> itemIds = itemGroups.stream().map(itemGroup -> itemGroup.getItemId()).collect(Collectors.toList());
            Map<String, Object> map = new HashMap<>();
            map.put("ids",itemIds);
            String body = HttpRequest.post("http://192.168.127.142:8082/item/groupItems")
                    .body(JSONObject.toJSONString(map))
                    .execute()
                    .body();
            group.setItemNames(body);
            itemNames += body;
        }
        String result = groupNames + "|" + itemNames;
        System.out.println(result);
        return result;
    }

    @GetMapping("invoke")
    public void test(Integer id) {
        System.out.println("--->"+id);
    }
}
